package com.ebt.m.update;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.TextUtils;

import com.ebt.m.AppContext;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.utils.StateManager;
import com.ebt.m.utils.TimeUtils;
import com.ebt.m.utils.android.WebServiceRequestHelper;
import com.ebt.m.commons.utils.NetUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class UpdateService {
    public static final String NO_APK = "NO_APK";
    private Activity ctx;
    private static String TAG = "UpdateService";
    public OnCheckVersionListener onCheckVersionListener;

    public UpdateService(Activity context) {
        this.ctx = context;
    }

    public void updateVersion(OnCheckVersionListener listener) {
        if (!NetUtils.isNetworkConnected(ctx)) {
            return;
        }
        setOnCheckVersionListener(listener);
        if (onCheckVersionListener != null) {
            onCheckVersionListener.onCheckStarted();
        }
        StateManager.getInstance(ctx).setBoolean(StateManager.SETTING_ABOUT_NEW_HAS_APK, false);
        StateManager.getInstance(ctx).setString(StateManager.SETTING_ABOUT_NEW_APK_URL, null);
        Observable.just("")
                .doOnNext(s -> run())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(s1 -> initUpdateVersion(), throwable -> {
                    if (onCheckVersionListener != null) {
                        onCheckVersionListener.onCheckFinished(false);
                    }
                    Logger.e(throwable.getMessage());
                });
    }

    private void initUpdateVersion() {
        boolean hasNewApk = StateManager.getInstance(ctx).getBoolean(StateManager.SETTING_ABOUT_NEW_HAS_APK);
        String apkUrl = StateManager.getInstance(ctx).getString(StateManager.SETTING_ABOUT_NEW_APK_URL);
        if (hasNewApk && !TextUtils.isEmpty(apkUrl)) {
            UpdateDialogUtil.showUpdateUtil(ctx, apkUrl, null);
            if (onCheckVersionListener != null) {
                onCheckVersionListener.onCheckFinished(true);
            }
            return;
        }
        if (onCheckVersionListener != null) {
            onCheckVersionListener.onCheckFinished(false);
        }
    }

    public static String getApkVersionCode() {
        String localVersion = NO_APK;
        try {
            PackageInfo packageInfo = AppContext.getInstance().getPackageManager().getPackageInfo(AppContext.getInstance().getPackageName(), 0);
            localVersion = packageInfo.versionCode + "";
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    public static String getApkVersionName() {
        String localVersion = NO_APK;
        try {
            PackageInfo packageInfo = AppContext.getInstance().getPackageManager().getPackageInfo(AppContext.getInstance().getPackageName(), 0);
            localVersion = packageInfo.versionName + "";
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    public interface OnCheckVersionListener {
        void onCheckStarted();

        void onCheckFinished(boolean hasNewVersion);
    }

    public void setOnCheckVersionListener(OnCheckVersionListener listener) {
        this.onCheckVersionListener = listener;
    }

    /**
     * 获取服务器EBT.app.apk版本号
     *
     * @return
     */
    public ResultCheckUpdateApk checkUpdateApk() throws Exception {
        JSONObject jsonParams = new JSONObject();
        jsonParams.put("ServiceName", "GetEBTVersionInfo");
        JSONObject versionNo = new JSONObject();
        versionNo.put("name", "VersionCode");
        versionNo.put("value", getApkVersionCode());
        JSONObject clientObj = new JSONObject();
        clientObj.put("name", "ClientType");
        clientObj.put("value", "PhoneAndroid");
        JSONObject company = new JSONObject();
        company.put("name", "CompanyId");
        company.put("value", ConfigData.COMPANY_ID);
        JSONArray parameters = new JSONArray();
        parameters.put(versionNo);
        parameters.put(clientObj);
        parameters.put(company);
        jsonParams.put("Parameters", parameters);

        Map<String, String> pamps = new HashMap<String, String>();
        pamps.put("strJson", jsonParams.toString());
        String res = WebServiceRequestHelper.sendRequestByNoAccount(pamps, ConfigData.URL_CAS_WSDL, ConfigData.URL_CAS_REQUESTDEVICESERVICE_ACTION, ConfigData.URL_CAS_REQUESTDEVICESERVICE_METHOD, ConfigData.URL_CAS_XMLNS);
        Logger.json(TAG, res);
        JSONObject jsonObject = new JSONObject(res);
        String isLatestVersion = jsonObject
                .getString("IsLatestVersion");
        if (isLatestVersion.equals("false")) {
            JSONObject latestVersion = jsonObject
                    .getJSONObject("LatestVersion");
            List<VersionLog> versionList = new ArrayList<VersionLog>();
            JSONArray versionLogArray = jsonObject
                    .getJSONArray("VersionLog");
            int length = versionLogArray.length();
            for (int i = 0; i < length; i++) {
                JSONObject versionLogJson = (JSONObject) versionLogArray
                        .get(i);
                VersionLog vl = new VersionLog(
                        versionLogJson.getString("Module"),
                        versionLogJson.getString("Category"),
                        versionLogJson.getString("Description"),
                        versionLogJson.getString("ReleaseDate"),
                        versionLogJson.getString("VersionID"));
                versionList.add(vl);
            }
            return new ResultCheckUpdateApk(true,
                    latestVersion.getString("VersionAddress"),
                    latestVersion.getString("VersionID"), versionList, null);
        } else {// 没有新版本
            return new ResultCheckUpdateApk(false, null, null, null, null);
        }
    }

    public void run() {
        ResultCheckUpdateApk result;
        try {
            result = checkUpdateApk();
            if (result != null && result.hasNewApk) {
                setApkVersionState(true);
                setApkCheckTime();
                StateManager.getInstance(ctx).setString(StateManager.SETTING_ABOUT_NEW_APK_URL, result.apkUrl);
                StateManager.getInstance(ctx).setString(StateManager.SETTING_ABOUT_NEW_APK_UPDATE_CONTENT, result.getVersionLog());
            } else {
                setApkVersionState(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            setApkVersionState(false);

        }
    }

    private void setApkVersionState(boolean hasNew) {
        if (hasNew) {
            StateManager.getInstance(ctx).setBoolean(StateManager.SETTING_ABOUT_NEW_HAS_APK, true);
        } else {
            StateManager.getInstance(ctx).setBoolean(StateManager.SETTING_ABOUT_NEW_HAS_APK, false);
        }
    }

    private void setApkCheckTime() {
        String last_sync_time = TimeUtils.dateTime2String(new Date());
        if (last_sync_time == null || last_sync_time.length() == 0) {

        } else {
            StateManager.getInstance(ctx).setString(StateManager.SETTING_ABOUT_APK_CHECK_TIME, last_sync_time);
        }
    }

}
